package com.jyxd.web.mq;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jyxd.web.data.basic.NurseRecordForm;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.hiscz.dto.TemperatureSheet;
import com.jyxd.web.service.patient.PatientService;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

@Component
public class TemperatureSheetReceiver {

    @Value("${icu.job.mq.temperature-sheet-update.queue}")
    private String temperatureSheetQueue;
    @Value("${icu.temperature-sheet-update.url}")
    private String url;
    private final Logger logger = LoggerFactory.getLogger(TemperatureSheetReceiver.class);
    @Autowired
    private PatientService patientService;

    @RabbitListener(queuesToDeclare = @Queue("#{temperatureSheetQueue}"))
    public void process(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, @Payload NurseRecordForm nurseRecordForm) throws IOException {
        logger.info("当前插入时间:{},护理单时间:{}", DateUtil.formatDateTime(new Date()), DateUtil.formatDateTime(nurseRecordForm.getDataTime()));
        logger.info("NurseRecordForm:{}", nurseRecordForm);
        //调用数据中心推送数据
        try {
            //判断该数据时间  只有3,7,11,15,19,23数据需要推送
            Date dataTime = nurseRecordForm.getDataTime();
            if (Objects.isNull(dataTime)) {
                return;
            }

            Patient patient = patientService.queryData(nurseRecordForm.getPatientId());
            if (Objects.isNull(patient)) {
                return;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dataTime);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (StrUtil.equalsAny(String.valueOf(hour), "3", "7", "11", "15", "19", "23")) {
                TemperatureSheet temperatureSheet = buildTemperatureSheet(nurseRecordForm, hour, patient);
                String result = HttpUtil.post(url, JSON.toJSONString(temperatureSheet));
                logger.info("数据中心推送体温单数据,TemperatureSheet:{}请求返回结果:{}", JSON.toJSONString(temperatureSheet), result);
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.containsKey("code")) {
                    String code = jsonObject.getString("code");
                    if (HttpStatus.HTTP_OK != Integer.parseInt(code)) {
                        logger.error("数据中心推送体温单数据,TemperatureSheet:{},请求异常，请求返回结果:{}", JSON.toJSONString(temperatureSheet), result);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("数据中心推送体温单数据,请求异常，异常信息:{}", e);
//            channel.basicNack(tag, false, true);
        } finally {
            channel.basicAck(tag, false);
        }
    }

    @Bean(name = "temperatureSheetQueue")
    public String getTemperatureSheetQueue() {
        return temperatureSheetQueue;
    }

    private TemperatureSheet buildTemperatureSheet(NurseRecordForm nurseRecordForm, int hour, Patient patient) {
        TemperatureSheet temperatureSheet = new TemperatureSheet();
        temperatureSheet.setVisitCode(patient.getVisitCode());
        temperatureSheet.setIRecordId(nurseRecordForm.getId());
        long cDayNum = (nurseRecordForm.getDataTime().getTime() - patient.getEnterTime().getTime()) / (24 * 3600 * 1000);
        temperatureSheet.setCDayNum(cDayNum + "");
        temperatureSheet.setDataTime(DateUtil.formatDateTime(nurseRecordForm.getDataTime()));
        temperatureSheet.setHr(nurseRecordForm.getHr());
        temperatureSheet.setPulse(nurseRecordForm.getPulse());
        temperatureSheet.setBr(nurseRecordForm.getBr());
        temperatureSheet.setAbp(nurseRecordForm.getAbp());
        temperatureSheet.setNbp(nurseRecordForm.getNbp());
        temperatureSheet.setBpType(hour > 12 ? "1" : "0");
        temperatureSheet.setTemperature(nurseRecordForm.getTemplate());
        temperatureSheet.setSpO2(nurseRecordForm.getSpO2());
        temperatureSheet.setITime(hour + "");
        temperatureSheet.setLrrID(StringUtils.isNotEmpty(nurseRecordForm.getOperatorCode()) ? nurseRecordForm.getOperatorCode() : nurseRecordForm.getOperatorCodeUpdate());
        temperatureSheet.setLrrxm(StringUtils.isNotEmpty(nurseRecordForm.getOperatorName()) ? nurseRecordForm.getOperatorName() : nurseRecordForm.getOperatorCodeUpdateName());
        temperatureSheet.setLrrsj(DateUtil.formatDateTime(nurseRecordForm.getCreateTime()));
        return temperatureSheet;
    }
}
